import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
// 用于和视图结合
import { Provider, connect } from 'react-redux'

class Counter extends React.Component {
  render () {
    // 计数, 通过store的state传给props, 直接通过props就可以将state的数据获取
    const value = this.props.value
    // 将修改数据的事件或方法传入到props
    const onAddClick = this.props.onAddClick
    // 等同于vuex的mapMutation mapState
    return (
      <div>
        <h2>计数数量: { value }</h2>
        <button onClick={ onAddClick }> + 1 </button>
        <button onClick={ this.props.onAddClick5 }> + 5 </button>
      </div>
    )
  }
}

const addAction = {
  type: 'add',
}

let actionFnObj = {
  add: (state, action) => {
    state.num++
    return state
  },
  addNum: (state, action) => {
    state.num = state.num + action.num
    return state
  }
}

function reducer(state={num: 0}, action) {
  if (action.type.indexOf('redux') === -1)
    state = actionFnObj[action.type](state, action)
  // switch(action.type) {
  //   case 'add':
  //     state.num++
  //     break
  //   case 'addNum':
  //     state.num += 5
  //     break
  //   default: break
  // }
  return { ...state }
}

const store = createStore(reducer)

// 将state映射到props函数
function mapStateToProps(state) {
  return {
    value: state.num
  }
}
// 将修改state数据的方法, 映射到props, 默认会传入store里的dispatch方法
function mapDispatchToProps (dispatch) {
  return {
    onAddClick: () => { dispatch(addAction) },
    onAddClick5: () => { dispatch({ type: 'addNum', num: 5 }) }
  }
}

// 将上面的2个方法, 将数据仓库的state和修改state的方法映射到组件上, 形成新的组件
const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)

ReactDOM.render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('root')
)
